// 登录页面

import React, {Component} from 'react';

import {DeviceEventEmitter, StatusBar,Keyboard, TouchableNativeFeedback, Text, View, ImageBackground, Image, TextInput, Button, StyleSheet, PixelRatio} from 'react-native';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'

import loginActions from '../../../store/actions/login';
import {Actions} from 'react-native-router-flux';
import {mainBackgroundColor, white} from "../../../style/global";
import Tips from 'react-native-root-tips';
import AwesomeAlert from 'react-native-awesome-alerts';
import {RNUSBPrinter} from "react-native-usb-printer-mi";
const Buffer = require('buffer').Buffer;

class LoginPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            userName: '',
            passWord: '',
            showLoading: false,
            devices: [],
            isPrint: false
        };
    }

    componentDidMount = async () => {
        /*storage.load({
            key:'user-token'
        }).then(res => {
           if (res) {
               Actions.reset('IndexPage');
               return
           }
        }).catch(err => {

        });*/
        const devices = await RNUSBPrinter.getUSBDeviceList();
        if (devices && devices.length) {
            let vendorId = '';
            let productId = '';
            let isPrint = false;
            let printedSelected = '';
            devices.forEach(item => {
                console.log('这个是每个item', item);
                if (item.device_type == 7) {
                    vendorId = item.vendor_id;
                    productId = item.product_id;
                    isPrint = true;
                    this.setState({
                        isPrint: isPrint
                    })
                }
            });
            if (isPrint) {
                printedSelected = await RNUSBPrinter.connectPrinter(vendorId, productId);
            }
            this.setState(Object.assign({}, this.state, {
                printedSelected: printedSelected,
                devices: devices,
            }));
            console.log('到底在哪里授权', devices);
        }
        this.listener = DeviceEventEmitter.addListener('userLogin', (status, message) => {
            if (!status) {
                Tips.showFail(message);
            } else {
                Actions.reset('IndexPage');
            }
            this.setState({
                showLoading: false
            })
        })
    };
    componentWillUnmount() {
        this.listener.remove();
    }

    userInputChange(value) {
        this.setState({
            userName: value.text
        });
    }
    passwordChange(value) {
        this.setState({
            passWord: value.text
        });
    }

    _userLogin() {
        let {login} = this.props;

        if (!this.state.userName || this.state.userName.length == 0) {
            Tips.show('请输入账号');
            return
        }
        if (!this.state.passWord || this.state.passWord.length == 0) {
            Tips.show('请输入密码');
            return
        }
        this.setState({
            showLoading: true
        });
        Keyboard.dismiss();
        login.userLogin(this.state.userName, this.state.passWord);
    }

    render() {
        return (
            <View style={style.loginPage}>
                <StatusBar hidden={true} />
                 <ImageBackground source={require("../../../img/login-bg.png")} style={style.img}>
                    <View style={style.loginBox}>
                        <View style={style.login}>
                            <View style={style.avatarBox}>
                                <Image source={require('../../../img/avatar.png')}></Image>
                            </View>
                            <TextInput
                                style={style.input}
                                placeholder='请输入账号'
                                onChangeText={(text) => this.userInputChange({text})}
                                value={this.state.text}
                            />
                            <TextInput
                                style={style.input}
                                placeholder='请输入密码'
                                secureTextEntry={true}
                                onChangeText={(text) => this.passwordChange({text})}
                                value={this.state.text}
                            />

                            <TouchableNativeFeedback onPress={()=> this._userLogin()}>
                                <View style={style.button}>
                                    <Text style={{color: white}}>
                                        登录
                                    </Text>
                                </View>
                            </TouchableNativeFeedback>
                        </View>
                    </View>
                </ImageBackground>

                {/*登录loading*/}
                <AwesomeAlert
                    showProgress={true}
                    show={this.state.showLoading}
                    title='正在登录'
                    closeOnTouchOutside={false}
                    closeOnHardwareBackPress={false}
                >

                </AwesomeAlert>
            </View>
        )
    }
}

const style = StyleSheet.create({
    loginPage: {
        width: '100%',
        height: '100%',
    },
    img: {
        width: '100%',
        height: '100%',
    },
    spinnerTextStyle: {
      color: white
    },
    loginBox: {
        height: 400,
        flexDirection: 'row',
        justifyContent: 'center',
        marginTop: 50
    },
    login: {
        width: 540,
        height: 'auto',
        backgroundColor: '#fff',
        padding: 50,
        borderRadius: 2
    },
    avatarBox: {
        flexDirection: 'row',
        justifyContent: 'center',
        marginBottom: 36
    },
    input: {
        height: 50,
        borderColor: '#D8D8D8',
        paddingLeft: 20,
        borderWidth: 1,
        borderRadius: 2,
        marginBottom: 13,
    },
    button: {
        marginTop: 10,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        color: white,
        backgroundColor: mainBackgroundColor,
        borderRadius: 4

    }
});

export default connect(state => ({state}), dispatch => ({
        login: bindActionCreators(loginActions, dispatch)
    })
)(LoginPage)

// export default LoginPage;

